<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\UserPoints;
use think\Request;
use think\Db;
use think\Validate;

/**
 * 幸运分API控制器
 */
class LuckyPoints extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];

    /**
     * 领取幸运分
     */
    public function claim(Request $request)
    {
        // 获取当前用户
        $user = $this->auth->getUser();
        if (!$user) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        // 检查今日是否已领取
        $today = date('Y-m-d');
        $existingRecord = Db::name('user_points')
            ->where('user_id', $user['uid'])
            ->where('source', 'lucky_points')
            ->whereTime('create_time', 'between', [strtotime($today . ' 00:00:00'), strtotime($today . ' 23:59:59')])
            ->find();

        if ($existingRecord) {
            return json(['code' => 400, 'msg' => '今日已领取，明天再来吧！']);
        }

        // 获取请求数据，设置默认值
        $data = $request->post();
        $data['points'] = $data['points'] ?? 3; // 默认3分
        $data['source'] = $data['source'] ?? 'lucky_points';
        $data['description'] = $data['description'] ?? '每日签到获得幸运分';
        
        // 验证数据
        $validate = new Validate();
        $validate->rule([
            'points' => 'number|between:1,10',
            'source' => 'max:50',
            'description' => 'max:255'
        ]);

        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        try {
            // 开始事务
            Db::startTrans();

            // 添加积分记录
            $pointsData = [
                'user_id' => $user['uid'],
                'points' => $data['points'],
                'source' => $data['source'],
                'description' => $data['description'],
                'create_time' => time(),
                'update_time' => time(),
                'date'=>date("Y-m-d", time()),
                'status' => 1
            ];

            $result = Db::name('user_points')->insert($pointsData);

            if (!$result) {
                throw new \Exception('积分记录添加失败');
            }

            // 更新用户总积分
            $userModel = Db::name('user');
            $currentPoints = $userModel->where('id', $user['uid'])->value('points') ?: 0;
            $newPoints = $currentPoints + $data['points'];
            
            $updateResult = $userModel->where('id', $user['uid'])->update([
                'points' => $newPoints,
                'updatetime' => time()
            ]);

            if (!$updateResult) {
                throw new \Exception('用户积分更新失败');
            }

            // 提交事务
            Db::commit();

            return json([
                'code' => 200,
                'msg' => '领取成功',
                'data' => [
                    'points_earned' => $data['points'],
                    'total_points' => $newPoints,
                    'source' => $data['source'],
                    'description' => $data['description']
                ]
            ]);

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            
            return json([
                'code' => 500,
                'msg' => '领取失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 检查今日是否已领取幸运分
     */
    public function checkTodayStatus(Request $request)
    {
        // 获取当前用户
        $user = $this->auth->getUser();
        if (!$user) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }

        // 检查今日是否已领取
        $today = date('Y-m-d');
        $existingRecord = Db::name('user_points')
            ->where('user_id', $user['uid'])
            ->where('source', 'lucky_points')
            ->where('DATE(create_time)', $today)
            ->find();

        return json([
            'code' => 200,
            'data' => [
                'claimed' => !empty($existingRecord),
                'date' => $today
            ]
        ]);
    }
}